import config from './configs';
class SSEService {
    private source: EventSource | null = null;
    private url: string;
  
    constructor(url: string) {
      this.url = url;
    }
  
    public connect(): void {
      const url = `${config.baseUrl}/${this.url}`;
      this.source = new EventSource(url);
  
      this.source.addEventListener('open', this.handleOpen.bind(this));
      this.source.addEventListener('message', this.handleMessage.bind(this));
      this.source.addEventListener('error', this.handleError.bind(this));
    }
  
    private handleOpen(event: Event): void {
      console.log("建立连接。。。");
    }
  
    private handleMessage(event: MessageEvent): void {
      console.log(event.data);
      // 你可以在这里处理接收到的数据
    }
  
    private handleError(event: Event): void {
      if (this.source && this.source.readyState === EventSource.CLOSED) {
        console.log("连接关闭");
      } else {
        console.error(event);
      }
    }
  
    public close(): void {
      if (this.source) {
        this.source.close();
        this.source = null;
      }
    }
  }
  
  export default SSEService;